package org.jeecg.modules.wlhy.captain.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.wlhy.captain.entity.HyCaptain;
import org.jeecg.modules.wlhy.captain.entity.HyCaptainVehicle;
import org.jeecg.modules.wlhy.captain.entity.HyOrderCaptain;
import org.jeecg.modules.wlhy.captain.entity.ImportHyCaptainDTO;
import org.jeecg.modules.wlhy.captain.mapper.HyCaptainMapper;
import org.jeecg.modules.wlhy.captain.mapper.HyCaptainVehicleMapper;
import org.jeecg.modules.wlhy.captain.mapper.HyOrderCaptainMapper;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainService;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainVehicleService;
import org.jeecg.modules.wlhy.hybank.service.IHyBankService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.mapper.HyDriverMapper;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.mapper.HyVehicleMapper;
import org.jeecg.modules.wlhy.order.entity.HyOrderApiDTO;
import org.jeecg.modules.wlhy.order.mapper.HyOrderMapper;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import static org.jeecg.common.constant.CommonConstant.DEL_FLAG_0;

/**
 * @Description: hy_captain
 * @Author: jeecg-boot
 * @Date:   2024-11-07
 * @Version: V1.0
 */
@Service
public class HyCaptainServiceImpl extends ServiceImpl<HyCaptainMapper, HyCaptain> implements IHyCaptainService {


    @Resource
    private HyDriverMapper hyDriverMapper;

    @Resource
    private HyVehicleMapper hyVehicleMapper;

    @Resource
    private HyCaptainVehicleMapper hyCaptainVehicleMapper;
    
    @Resource
    private HyOrderMapper hyOrderMapper;
    @Resource
    private HyOrderCaptainMapper hyOrderCaptainMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysUserRoleService sysUserRoleService ;

    @Value(value = "${captain.captain-role-id}")
    private String captainRoleID;
    @Autowired
    private IHyBankService hyBankService;

    @Autowired
    private IHyCaptainVehicleService hyCaptainVehicleService;

    @Autowired
    private UserUtil userUtil;

    @Override
    public HyCaptain getInfoByUserId(String userId) {

        HyCaptain captain = new HyCaptain();
        captain.setUserId(userId);
        HyCaptain captainInfo = baseMapper.selectOne(new QueryWrapper<HyCaptain>().eq("user_id", userId));
        if (captainInfo!= null) {
            return captainInfo;
        }

        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteById(String id) {
        //根据承运商id获取所有车辆信息和司机信息
        List<HyDriver> driverList = hyDriverMapper.getDriverListByCarrierId(id);
        List<HyVehicle> vehicleList = hyVehicleMapper.getVehicleListByCarrierId(id);
        //修改车辆信息和司机信息的承运商id为""
        for (HyDriver driver : driverList) {
            driver.setCarrierId("");
            hyDriverMapper.updateById(driver);
        }
        for (HyVehicle vehicle : vehicleList) {
            vehicle.setCarrierId("");
            hyVehicleMapper.updateById(vehicle);
        }
        //删除承运商与车辆的关联表
        Integer num = hyCaptainVehicleMapper.selectCount(new QueryWrapper<HyCaptainVehicle>().eq("captain_id", id));
        int count=1;
        if (num != 0) {
             count = hyCaptainVehicleMapper.delete(new QueryWrapper<HyCaptainVehicle>().eq("captain_id", id));
        }

        //删除承运商信息
        int count1 = baseMapper.deleteById(id);
        if (count1 == 0||count==0){
            throw new RuntimeException("删除失败");
        }
        return 1;
    }

    @Override
    public Result checkData(String orderId, String captainId, String carrierFeeType, String carrierUnitFee) {
        HyOrderApiDTO orderInfo = hyOrderMapper.getInfoById(orderId);
        if (StringUtils.isEmpty(orderId)) {
            return Result.error("订单信息不能为空");
        }
        if (StringUtils.isEmpty(carrierFeeType)) {
            return Result.error("运费计算方式不能为空");
        }
        if (StringUtils.isEmpty(carrierUnitFee)) {
            return Result.error("运费单价不能为空");
        }
        if (StringUtils.isEmpty(captainId)) {
            return Result.error("承运商信息不能为空");
        }
        if (orderInfo.getShippingUnitPrice().compareTo(new BigDecimal(carrierUnitFee)) < 0) {
            return Result.error("承运商运费单价不能大于司机运费单价");
        }
        return Result.OK("校验成功");
    }

    /**
     * 绑定
     * @param orderId
     * @param captainId
     * @param carrierFeeType
     * @param carrierUnitFee
     * @return
     */
    @Override
    public Result binding(String orderId, String captainId, String carrierFeeType, String carrierUnitFee) {

        HyOrderApiDTO order = hyOrderMapper.getInfoById(orderId);
        if (order == null) {
            return Result.error("货源不存在");
        }
        //如果货源的支付类型为代收人模式，则返回错误信息
        if (order.getPayType().equals("2")) {
            return Result.error("代收人模式下不能进行承运商派单");
        }
        if ("8".equals(order.getOrderStatus())) {
            return Result.error("该货源已完结,不能接单");
        }
        if (!"2".equals(order.getOrderStatus())) {
            return Result.error("该货源未发布,不能接单");
        }
        //判断承运商是否存在
        HyCaptain captain = baseMapper.selectById(captainId);
        if (captain == null) {
            return Result.error("承运商不存在");
        }

        //添加承运商与货源关联表
        HyOrderCaptain hyOrderCaptain = new HyOrderCaptain();
        hyOrderCaptain.setOrderId(orderId);
        hyOrderCaptain.setCaptainId(captainId);
        hyOrderCaptain.setCarrierFeeType(carrierFeeType);
        hyOrderCaptain.setCarrierUnitFee(new BigDecimal(carrierUnitFee));
        hyOrderCaptainMapper.insert(hyOrderCaptain);

        return Result.OK("绑定成功");
    }

    //批量导入承运商
    @Override
    public void saveBatchCaptain(List<ImportHyCaptainDTO> list) {
        //保存用户
        List<SysUser> sysUsers  = list.stream().map(
                item -> ImportHyDriverDTOTOSysUser(item)
        ).collect(Collectors.toList());

        sysUserService.saveBatch(sysUsers);
        //保存用户部门和角色
        List<SysUserRole> userRoles = new ArrayList();
        HashMap<String, String> userIDMap = new HashMap<>();

        for(SysUser user :sysUsers){
            SysUserRole userRole = new SysUserRole(user.getId(), captainRoleID);
            userRoles.add(userRole);
            userIDMap.put(user.getPhone(),user.getId());
        }
        sysUserRoleService.saveBatch(userRoles) ;

        //保存承运商
        List<HyCaptain> captains  = list.stream().map(
                item -> ImportImportHyCaptainDTOTOHyCaptain(item ,userIDMap.get(item.getLoginPhone()))
        ).collect(Collectors.toList());
        this.saveBatch(captains);

        //关联车辆
        List<HyCaptainVehicle> hyCaptainVehicleList  = new ArrayList<>();
        for (ImportHyCaptainDTO dto : list) {
            if (StringUtils.isEmpty(dto.getVehicleNumberList())){
                continue;
            }
            String[] vehicleNumberList = dto.getVehicleNumberList().split(",");
            for (String vehicleNumber : vehicleNumberList) {
                HyVehicle vehicle = hyVehicleMapper.getHyVehicleByVehicleNumber(vehicleNumber);
                if (vehicle != null) {
                    HyCaptain captain = baseMapper.selectOne(new QueryWrapper<HyCaptain>().eq("login_phone",dto.getLoginPhone()));
                    if (hyCaptainVehicleService.list(new QueryWrapper<HyCaptainVehicle>().eq("captain_id",captain.getId()).eq("vehicle_id",vehicle.getId())).size() > 0){
                        continue;
                    } else if (vehicle.getCarrierId()!= null) {
                        continue;
                    }
                    HyCaptainVehicle captainVehicle = new HyCaptainVehicle();
                    captainVehicle.setCaptainId(captain.getId());
                    captainVehicle.setVehicleId(vehicle.getId());
                    captainVehicle.setUserId(captain.getUserId());
                    hyCaptainVehicleList.add(captainVehicle);
                    vehicle.setCarrierId(captain.getId());
                    hyVehicleMapper.updateById(vehicle);
                }
            }
        }
        hyCaptainVehicleService.saveBatch(hyCaptainVehicleList);
    }

    private HyCaptain ImportImportHyCaptainDTOTOHyCaptain(ImportHyCaptainDTO importHyCaptainDTO, String userId) {

        if (importHyCaptainDTO == null) {
            return null;
        }
        HyCaptain hyCaptain = new HyCaptain();
        hyCaptain.setUserId(userId);
        hyCaptain.setUserName(importHyCaptainDTO.getUserName());
        hyCaptain.setCaptainName(importHyCaptainDTO.getCaptainName());
        hyCaptain.setLoginPhone(importHyCaptainDTO.getLoginPhone());
        hyCaptain.setIzUsed("1");
        hyCaptain.setDelFlag("0");
        hyCaptain.setCreateBy(userUtil.getLoginUser().getRealname());

        hyCaptain.setCreateTime(new Date());
        hyCaptain.setBankName(importHyCaptainDTO.getBankName());
        hyCaptain.setBankNum(importHyCaptainDTO.getBankNum());
        hyCaptain.setIdcard(importHyCaptainDTO.getIdcard());
        hyCaptain.setKhTel(importHyCaptainDTO.getKhTel());


        hyCaptain.setIdcardImg(importHyCaptainDTO.getIdcardImg());
        hyCaptain.setIdcardImgBack(importHyCaptainDTO.getIdcardImgBack());

        hyCaptain.setBankType(importHyCaptainDTO.getBankType());
        hyCaptain.setCrBankNo(importHyCaptainDTO.getCrBankNo());
        //选项
        if (importHyCaptainDTO.getBankImgFront()!= null) {
            hyCaptain.setBankImgFront(importHyCaptainDTO.getBankImgFront());
        }
        if (importHyCaptainDTO.getIdcardImg()!= null) {
            hyCaptain.setIdcardImg(importHyCaptainDTO.getIdcardImg());
        }
        if (importHyCaptainDTO.getIdcardImgBack()!= null) {
            hyCaptain.setIdcardImgBack(importHyCaptainDTO.getIdcardImgBack());
        }
        return hyCaptain;
    }

    private  SysUser ImportHyDriverDTOTOSysUser(ImportHyCaptainDTO importHyCaptainDTO){
        if (importHyCaptainDTO == null) {
            return null;
        }
        SysUser user = new SysUser();
        String phone = importHyCaptainDTO.getLoginPhone();
        user.setCreateTime(new Date());
        user.setUsername(importHyCaptainDTO.getUserName());
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        //设置默认密码123456
        user.setPassword("Aa.123456");
        String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
        user.setPassword(passwordEncode);
        user.setRealname(importHyCaptainDTO.getCaptainName());
        user.setPhone(phone);
        user.setActivitiSync(CommonConstant.ACT_SYNC_0);
        user.setStatus(CommonConstant.USER_UNFREEZE);
        user.setDelFlag(DEL_FLAG_0);
        user.setCreateBy("管理员");
        user.setUType("7");

        return  user;
    }
}
